class Solution {
    public char[][] board;
    public char[] chars;
    public boolean exist(char[][] board, String word) {
        this.board = board;
        this.chars = word.toCharArray();
        for(int i = 0; i < board.length; i++) {
            for(int j = 0; j < board[0].length; j++) {
                if(hasPath(i, j, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean hasPath(int i, int j, int k) {
        if(i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != chars[k]) {
            return false;
        }
        if(k == chars.length - 1) {
            return true;
        }
        char temp = board[i][j];
        board[i][j] = '/';
        if(hasPath(i - 1, j, k + 1)) {
            return true;
        }
        if(hasPath(i + 1, j, k + 1)) {
            return true;
        }
        if(hasPath(i, j + 1, k + 1)) {
            return true;
        }
        if(hasPath(i, j - 1, k + 1)) {
            return true;
        }
        board[i][j] = temp;
        return false;
    }
}